﻿#include "MyHttp.h"
#include <QEventLoop>
#include <QSharedPointer>

#define NULL_RETURN_Y(x,y) if(nullptr==x){return y;}

MyHttp::MyHttp(QObject *parent) : QObject(parent)
{

}

QString MyHttp::Get(QString strUrl, QString strData)
{
    strUrl = strData.isEmpty() ? strUrl : (strUrl+"?"+strData);
    QUrl url(strUrl);
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");

    MyNetworkAccessManager accessManager;
    QNetworkReply* reply = accessManager.get(request);


    QEventLoop eloop;
    connect(reply, SIGNAL(finished()), &eloop, SLOT(quit()));
    eloop.exec();

    NULL_RETURN_Y(reply, "");
    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray baResponse = reply->readAll();
        QString strRet = QString::fromUtf8(baResponse);
        return strRet;
    }
    else
    {
        qDebug() << "error : " << reply->error();
        qDebug() << reply->errorString();
        qDebug() << "get : " << strUrl;
        qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).value<int>();
    }

    return "";
}

QString MyHttp::Post(QString strUrl, QString strData)
{
    strUrl +=  QString("?tm=%1").arg(QDateTime::currentMSecsSinceEpoch());
    QUrl url(strUrl);
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");

    MyNetworkAccessManager accessManager;
    QNetworkReply* reply = accessManager.post(request, strData.toUtf8());


    QEventLoop eloop;
    connect(reply, SIGNAL(finished()), &eloop, SLOT(quit()));
    eloop.exec();

    NULL_RETURN_Y(reply, "");
    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray baResponse = reply->readAll();
        QString strRet = QString::fromUtf8(baResponse);
        return strRet;
    }
    else
    {
        qDebug() << "error : " << reply->error();
        qDebug() << reply->errorString();
        qDebug() << "get : " << strUrl;
        qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).value<int>();
    }

    return "";
}
